<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Task;

use App\Model\Play;
use App\Model\PlayDatum;
use App\Utils\Enum;

class SyncMatchStatsTask extends BaseSyncTask
{
    public function execute(): void
    {
        parent::execute();
        $curId = 0;
        $success = 0;
        while (true) {
            $ingMatchList = Play::query()->where([['id', '>', $curId], ['match_status', '=', Enum\MatchEnum::MATCH_STATUS_ING]])->orderBy('id')->limit(100)->select()->get();
            if ($ingMatchList->isEmpty()) {
                break;
            }
            foreach ($ingMatchList as $match) {
                $this->syncInit($match['match_id']);
                $curId = $match['id'];
                $detail = $this->api->getMatchInfo($match['match_id']);
                if (empty($detail)) {
                    $this->logger->warning(sprintf('比赛 (match_id=%s) 通过接口获取详情失败', $match['match_id']));
                    continue;
                }
                //详情
                $matchInfo = &$detail['data']['result']['match'];
                $update = [
                    'match_status_id' => $matchInfo['statusId'],
                    'match_status' => $matchInfo['matchStatus'],
                    'times' => isset($matchInfo['times']) ? new_json_encode($matchInfo['times']) : '{}',
                ];
                //比赛状态变更
                if ($match['match_status'] != Enum\MatchEnum::MATCH_STATUS_END && $matchInfo['matchStatus'] == Enum\MatchEnum::MATCH_STATUS_END) {
                    $update['match_end_time'] = time();
                }
                //spMatchStatus
                if (isset($matchInfo['spMatchStatus'])) {
                    $update['sp_match_status'] = $matchInfo['spMatchStatus'];
                }
                if (!empty($matchInfo['videoUrl'])) {
                    $update['video_url'] = $matchInfo['videoUrl'];
                }
                if (!empty($detail['data']['result']['animation']['url'])) {
                    $update['animate_url'] = $detail['data']['result']['animation']['url'];
                }
                if (isset($matchInfo['vbScores'])) {
                    $update['vb_scores'] = new_json_encode($matchInfo['vbScores']);
                } else {
                    $update['home_team_scores'] = new_json_encode($detail['data']['result']['match']['homeScores']);
                    $update['away_team_scores'] = new_json_encode($detail['data']['result']['match']['awayScores']);
                }
                $extend = [];
                $fields = [];
                //场馆信息
                if (isset($matchInfo['venue'])) {
                    $fields[] = '场馆';
                    $extend['venue'] = new_json_encode($matchInfo['venue']);
                }
                //指数 10min
                if ($this->toSync('odds')) {
                    $matchOdds = $this->api->getMatchOdds($match['match_id']);
                    if ($matchOdds && !empty($matchOdds['data']['result'])) {
                        $fields[] = '指数';
                        $extend['odds'] = new_json_encode($matchOdds['data']['result']);
                        $this->setSyncFlag('odds');
                    }
                }

                if ($match['sport_id'] == Enum::SPORT_TENNIS) {
                    //网球分数
                    if (isset($detail['data']['result']['tennisScores'])) {
                        $fields[] = '网球得分';
                        $update['tennis_scores'] = new_json_encode($detail['data']['result']['tennisScores']['data']);
                    }
                    //网球状态
                    if (isset($detail['data']['result']['tennisSetStats'])) {
                        $fields[] = '网球状态';
                        $extend['stats'] = new_json_encode($detail['data']['result']['tennisSetStats']['sets']['_$0']['items']);
                    }
                } else {
                    //状态
                    if ($this->toSync('stats')) {
                        $matchStats = $this->api->getMatchStats($match['match_id']);
                        if ($matchStats && !empty($matchStats['data']['result']['items'])) {
                            $fields[] = '状态';
                            $extend['stats'] = new_json_encode($matchStats['data']['result']);
                            $this->setSyncFlag('stats');
                        }
                    }
                }

                //趋势
                if (($match['sport_id'] == Enum::SPORT_FOOTBALL || $match['sport_id'] == Enum::SPORT_BASKETBALL) && $this->toSync('trend')) {
                    $matchTrend = $this->api->getMatchTrend($match['match_id']);
                    if ($matchTrend && !empty($matchTrend['data'])) {
                        $fields[] = '趋势';
                        $extend['trend'] = new_json_encode($matchTrend['data']['result']);
                        $this->setSyncFlag('trend');
                    }
                }

                //重要事件
                if ($match['sport_id'] == Enum::SPORT_FOOTBALL && $this->toSync('incidents')) {
                    $matchIncidents = $this->api->getMatchIncidents($match['match_id']);
                    if ($matchIncidents && !empty($matchIncidents['data'])) {
                        $fields[] = '重要事件';
                        $extend['incidents'] = new_json_encode($matchIncidents['data']['result']);
                        $this->setSyncFlag('incidents');
                    }
                }

                // 篮球比赛文字直播
                if ($match['sport_id'] == Enum::SPORT_BASKETBALL && $this->toSync('text_lives')) {
                    $matchTextLives = $this->api->getMatchTextLives($match['match_id']);
                    if (!empty($matchTextLives['data'])) {
                        $fields[] = '文字直播';
                        $extend['text_lives'] = new_json_encode($matchTextLives['data']['result']);
                        $this->setSyncFlag('text_lives');
                    }
                }
                Play::query()->where('id', $match['id'])->update($update);
                if (!empty($extend)) {
                    $ret = PlayDatum::query()->where('match_id', $match['match_id'])->update($extend);
                    if ($ret) {
                        $success++;
                        $this->logger->warning(sprintf('比赛数据更新 %s %s %s VS %s [%s]', $match['match_id'], date('Y-m-d H:i', $match['match_time']), $match['home_team_name'], $match['away_team_name'], implode(' ', $fields)));
                    }
                }
                unset($detail, $update, $extend);
            }
        }
        $this->logger->info(sprintf('成功更新[%d]场比赛相关状态', $success));
    }
}
